<template>
    <div
        ref="stBody"
        class="scroll-top__body"
        @scroll="onScroll">
        <slot></slot>
    </div>

    <div
        v-if="st"
        class="scroll-top__icon"
        @click="onTop">
        <van-circle
            v-model:current-rate="st"
            :rate="100"
            :stroke-width="80"
            class="flex-center"
            size="100%">
            <slot name="icon">
                <van-icon
                    name="down"
                    style="transform: rotateZ(180deg)" />
            </slot>
        </van-circle>
    </div>
</template>

<script lang="ts" setup>
    import { ref } from 'vue';

    const st = ref(0);
    const onScroll = (e) => {
        const { scrollTop, scrollHeight, clientHeight } = e.target;
        if (scrollTop > 250) {
            st.value = Math.floor((100 * (scrollTop + clientHeight)) / scrollHeight);
        } else {
            st.value = 0;
        }
    };

    const stBody: any = ref(null); // 根节点实例
    const onTop = () => {
        const step = Math.ceil(stBody?.value.scrollTop / 50);
        const c = setInterval(() => {
            if (stBody.value.scrollTop > 10) {
                stBody.value.scrollTop -= step;
            } else {
                stBody.value.scrollTop = 0;
                st.value = 0;
                clearInterval(c);
            }
        }, 1);
    };
</script>

<style lang="scss" scoped>
    .scroll-top__body {
        max-height: 100vh;
        word-break: break-word;
        overflow-x: hidden;
        overflow-y: scroll;
    }

    .scroll-top__icon {
        position: fixed;
        right: pxToRem(20);
        bottom: pxToRem(20);
        width: pxToRem(48);
        max-width: pxToRem(64);
        height: pxToRem(48);
        max-height: pxToRem(64);
        font-weight: bold;
        font-size: pxToRem(20);
        border-radius: 100%;
        background-color: #aedbff;
    }
</style>
